<?php 
namespace Admin\Model;
use Qiniu\Auth;

class CostDesignModel extends CommonModel{
	protected $fields = array('id','vouch_sn','cost_time','cost_type','cal_type','cost_fmoney','cost_desc','cost_tmoney','pro_id','com_id');

	// 检查这个月已存在的费用类型
	public function checkCost($time,$upd_id = 0){
		// 求出这个月的月初和月末时间戳
		$days = date('t',strtotime($time));
		$time = date('Y-m',strtotime($time));
		$start_time = strtotime($time.'-01');
		$end_time = strtotime($time.'-'.$days);

		if($upd_id){
			$cost_info = $this -> field('cal_type') -> where(array('cost_time' => array('between',$start_time.','.$end_time),'id' => array('neq',$upd_id))) -> select();
		}else{
			$cost_info = $this -> field('cal_type') -> where(array('cost_time' => array('between',$start_time.','.$end_time))) -> select();
		}
		

		if($cost_info){
			foreach($cost_info as $v){
				$cal_type[] = $v['cal_type'];
			}
			$cal_type = array_unique($cal_type);
		}else{
			$cal_type = array();
		}

		return $cal_type;
	}

	// 插入之前转化时间戳
	public function _before_insert(&$data){
		if(!$data['cost_time']){
			$this ->error = '时间不能为空！';
			return false;
		}

		$data['cost_time'] = strtotime($data['cost_time']);

		$this -> startTrans();
	}

	// 插入之后处理上传凭证，改变核算id选择状态
	public function _after_insert($data){
		// 接收上传的base64位上传文件编码
		$file = I('post.vimgs');
		// dump($file);exit;
		// 如果存在凭证上传文件
		if($file){
			// 引入必要的SDK文件
			include_once  'Qiniu/Auth.php';
			include_once  'Qiniu/Config.php';
			include_once  'Qiniu/functions.php';

			// 空间名
			$bucket = C('bucket');
			// 两个密钥
			$accessKey = C('accessKey');
			$secretKey = C('secretkey');

			// 七牛云外链域名
			$domain = C('qiniu_domain');

			// 上传图片接口地址
			$api = C('img_api');

			// 实例化授权类
			$auth = new Auth($accessKey, $secretKey);

			$upToken = $auth->uploadToken($bucket);//获取上传所需的token

			foreach($file as $k => $v){
				$v[0] = trim($v[0]);
				// 处理base64位数据，只要,以后的
				$pos=strpos($v[0],',');
				
				$str = substr($v[0],$pos+1);
				
				// 调用上传接口
				$res = qiniu_upload($api,$str,$upToken);

				// 将返回信息解码转为数组
				$res = json_decode($res,true);
				
				if($res['error']){
					// 如果存在错误信息
					$this ->error = $res['error'];
					return false;
				}else{
					$imgs[] = array(
						'cost_id' => $data['id'],
						'cost_key' => $res['key'],
						'cost_fname' => $v[1],
						'cost_fsize' => $v[2]
					);
				}			
			}

			// 插入凭证路径信息
			$pvoucher = M('cdesign_pvoucher');
			
			$res = $pvoucher -> addAll($imgs);
			
			if(!$res){
				$this -> rollback();
				$this ->after_error = 1;
				$this ->error = '新增凭证出错';
				return false;
			}
		}

		$this -> commit();
		return true;
	}

	public function _before_update(&$data){
		$id = $data['id'];
		// 查出原数组
		$old_data = $this -> where(array('id' => $id)) -> find();

		if($data['cost_time']){
			// 转化为时间戳
			$data['cost_time'] = strtotime($data['cost_time']);
		}

		if($old_data){
			// 与新更新的数据进行比较
			$data = array_diff_assoc($data, $old_data);

			if($data['cost_time']){
				$info = $this -> where(array('id' => array('neq',$id) , 'cost_time' => $data['cost_time'])) -> find();

				if($info){
					$this ->error = '时间不能重复！';
					return false;
				}
			}
			$data['id'] = $id;
		}

		$this -> startTrans();
	}

	public function _after_update($data){
		// 接收上传的base64位上传文件编码
		$file = I('post.vimgs');
			// 查到原来的凭证图片信息在更新新的凭证成功之后删除掉
			$pvoucher = M('cdesign_pvoucher');

			$pv_info = $pvoucher -> where(array('cost_id' =>$data['id'])) -> select();

			if($pv_info){
				// 删除原来的凭证路径信息
				$affec = $pvoucher -> where(array('cost_id' =>$data['id'])) -> delete();

				if($affec === false){
					$this ->error = '删除原凭证出错';
					$this -> rollback();
					$this ->after_error = 1;
					return false;
				}
			}
			
			// 引入必要的SDK文件
			include_once  'Qiniu/Auth.php';
			include_once  'Qiniu/Config.php';
			include_once  'Qiniu/functions.php';
			include_once  'Qiniu/Storage/BucketManager.php';
			include_once  'Qiniu/Http/Client.php';
			include_once  'Qiniu/Http/Request.php';
			include_once  'Qiniu/Http/Response.php';
			include_once  'Qiniu/Http/Error.php';
			// 空间名
			$bucket = C('bucket');
			// 两个密钥
			$accessKey = C('accessKey');
			$secretKey = C('secretkey');

			// 七牛云外链域名
			$domain = C('qiniu_domain');

			// 上传图片接口地址
			$api = C('img_api');

			// 实例化授权类
			$auth = new Auth($accessKey, $secretKey);

			if($file){
				// 如果存在新的再上传
				$upToken = $auth->uploadToken($bucket);//获取上传所需的token

				foreach($file as $k => $v){
					$v[0] = trim($v[0]);
					// 处理base64位数据，只要,以后的
					$pos=strpos($v[0],',');
					
					$str = substr($v[0],$pos+1);
					
					// 调用上传接口
					$res = qiniu_upload($api,$str,$upToken);

					// 将返回信息解码转为数组	
					$res = json_decode($res,true);
					
					if($res['error']){
						// 如果存在错误信息
						$this ->error = $res['error'];
						$this ->after_error = 1;
						return false;
					}else{

						$imgs[] = array(
							'cost_id' => $data['id'],
							'cost_key' => $res['key'],
							'cost_fname' => $v[1],
							'cost_fsize' => $v[2]
						);
					}			
				}

				// 插入新的凭证路径信息
				$res = $pvoucher -> addAll($imgs);
				
				if(!$res){
					$this ->error = '新增新凭证出错';
					$this -> rollback();
					$this ->after_error = 1;
					return false;
				}
			}

			$config = new \Qiniu\Config();

			// 删除凭证资源
			$bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);

			// 删除原来的图片资源
			if($pv_info){
				foreach($pv_info as $k=>$v){
					$bucketManager->delete($bucket, $v['cost_key']);
				}
			}

		$this -> commit();
		return true;
	}

	public function delCosts($cost_id){
		// 删除要做二件事情：删除本表数据、删除凭证表数据

		// 开启事物
		$this -> startTrans();

		
		// 删除本表数据
		$res1 = $this -> where(array('id' => array('in',$cost_id))) -> delete();

		if($res1 === false){
			$this ->error = '删除其他直接投入费用数据失败！';
			return false;
		}

		$vou_m = M('cdesign_pvoucher');
		// 查出来数据
		$vou_info = $vou_m -> where(array('cost_id' => array('in',$cost_id))) -> select();

		// 删除凭证表数据
		if($vou_info){
			// 删除关联凭证表数据
			$res2 = $vou_m -> where(array('cost_id' => array('in',$cost_id))) -> delete();

			if($res2 === false){
				$this ->error = '删除凭证数据失败！';
				$this -> rollback();
				return false;
			}

			// 引入必要的SDK文件
			include_once  'Qiniu/Auth.php';
			include_once  'Qiniu/Config.php';
			include_once  'Qiniu/functions.php';
			include_once  'Qiniu/Storage/BucketManager.php';
			include_once  'Qiniu/Http/Client.php';
			include_once  'Qiniu/Http/Request.php';
			include_once  'Qiniu/Http/Response.php';
			include_once  'Qiniu/Http/Error.php';
			// 空间名
			$bucket = C('bucket');
			// 两个密钥
			$accessKey = C('accessKey');
			$secretKey = C('secretkey');

			// 七牛云外链域名
			$domain = C('qiniu_domain');

			// 上传图片接口地址
			$api = C('img_api');

			// 实例化授权类
			$auth = new Auth($accessKey, $secretKey);

			$upToken = $auth->uploadToken($bucket);//获取上传所需的token

			$config = new \Qiniu\Config();

			// 删除凭证资源
			$bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);

			// 删除原来的图片资源
			foreach($vou_info as $k=>$v){
				$err = $bucketManager->delete($bucket, $v['cost_key']);

			}
					
		}
		
		$this -> commit();
		return true;
		
	}

	public function getCostDesigns(){
		// 必要条件,获取当前项目的燃料信息
		$pro_id = session('pro_id');
		

		$where['pro_id'] = $pro_id;

		// 接收时间条件
		$time = trim(I('get.time'));

		if($time){
			// 求出这个月天数
			$days = date('t',strtotime($time));

			// 求出这个月月初时间戳
			$start = strtotime($time.'-01');

			// 求出这个月月末的时间戳
			$end = strtotime($time.'-'.$days);

			$where['cost_time'] = array('between',$start.','.$end);
		}

		$type = intval(I('get.type'));

		if($type){
			$where['cal_type'] = $type;
		}


		// 获取总记录条数
		$count = $this->where($where)->count();

		// 实例化分页类
		$pagesize = 10;

		$page = new \Think\Page($count,$pagesize);

		$pagestr = $page->show();

		$p = intval(I('get.p'));

		$data = $this->where($where)->page($p,$pagesize)->select();
			
		foreach($data as $k => $v){
			$data[$k]['cost_time'] = date('Y年n月j日',$v['cost_time']);
			switch ($v['cost_type']) {
				case '1':
					$data[$k]['cost_type'] = '借';
					break;
				case '2':
					$data[$k]['cost_type'] = '贷-资本化';
					break;
				case '3':
					$data[$k]['cost_type'] = '贷-费用化';
					break;
			}
			switch ($v['cal_type']) {
				case '1':
					$data[$k]['cal_type'] = '新产品设计费';
					break;
				case '2':
					$data[$k]['cal_type'] = '新工艺规程制定费';
					break;
				case '3':
					$data[$k]['cal_type'] = '新药研制的临床试验费';
					break;
				case '4':
					$data[$k]['cal_type'] = '勘探开发技术的现场试验费';
					break;
			}
		}

		return array('pagestr'=>$pagestr,'data'=>$data);
	}
}
 ?>